const { validationResult } = require('express-validator');

// 自定义校验规则
const customValidations = {
    isValidDictCode: (value) => {
        // 字典编码只允许字母、数字和下划线，长度在2-50之间
        const regex = /^[a-zA-Z0-9_]{2,50}$/;
        return regex.test(value);
    },
    isValidDictName: (value) => {
        // 字典名称长度在2-100之间，不允许特殊字符
        const regex = /^[\u4e00-\u9fa5a-zA-Z0-9_\s]{2,100}$/;
        return regex.test(value);
    }
};

// 格式化验证错误信息
const formatErrors = (errors) => {
    return errors.array().map(error => ({
        field: error.param,
        message: error.msg,
        value: error.value
    }));
};

const validateRequest = (req, res, next) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        return res.json({
            code: 400,
            message: '请求参数验证失败',
            errors: formatErrors(errors)
        });
    }
    next();
};

module.exports = {
    validateRequest,
    customValidations
};